package crp.core.student.domain.repositories;

import com.qwlabs.lang.C2;
import com.qwlabs.panache.Where;
import crp.core.student.domain.models.StudentEntity;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import javax.validation.constraints.NotNull;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;

@ApplicationScoped
public class StudentRepository implements PanacheRepositoryBase<StudentEntity, String> {

    public Stream<StudentEntity> findByIds(Set<String> ids) {
        if (C2.isEmpty(ids)) {
            return Stream.empty();
        }
        return find("id in :ids", Parameters.with("ids", ids))
                .stream();
    }

    public Optional<StudentEntity> findByStudentNo(String studentNo) {
        return find("studentNo=:studentNo", Parameters.with("studentNo", studentNo))
                .firstResultOptional();
    }

    public PanacheQuery<StudentEntity> findBy(@NotNull String courseId) {
        Where where = Where.create()
                .and("id in (select distinct student.id from CourseEnrollmentEntity where course.id = :courseId )", "courseId", courseId);
        return find(where.get(), where.getParameters());
    }
}
